<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="课程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程类别" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入课程类别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.onsale_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="积分支付" prop="canPointPay">
        <el-select v-model="queryParams.canPointPay" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="老师" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入老师"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          size="small"
          v-model="uploadTime"
          @change="handleQuery"
          unlink-panels
          :picker-options="pickerOptions"
          　
          style="width: 220px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:courses:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:courses:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:courses:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:courses:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="coursesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="课程编号" align="center" prop="id"/>
      <el-table-column label="名称" align="center" prop="name" min-width="150"/>
      <el-table-column label="类别" align="center" prop="typeName" min-width="150"/>
      <el-table-column label="门店" align="center" prop="storeName" min-width="150"/><el-table-column label="标签" align="center" prop="tagIds"/ >
      <el-table-column label="图片地址" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="链接" align="center" prop="link"/>
      <el-table-column label="摘要" align="center" prop="desc"/>
      <el-table-column label="周几" align="center" prop="weekDesc"/>
      <el-table-column label="开始时间" align="center" prop="startTime"/>
      <el-table-column label="结束时间" align="center" prop="endTime"/>

      <!--
      <el-table-column label="具体时间" align="center" prop="timeInfo" />
      <el-table-column label="位置" align="center" prop="address" />
      <el-table-column label="纬度" align="center" prop="lat" />
      <el-table-column label="经度" align="center" prop="lon" />
      -->
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.onsale_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="人数限制" align="center" prop="num"/>
      <el-table-column label="每节课价格" align="center" prop="price" min-width="150"/>
      <el-table-column label="可以积分支付" align="center" prop="canPointPay" min-width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.canPointPay"/>
        </template>
      </el-table-column>
      <el-table-column label="可购买节数选项" align="center" prop="buyTimes" min-width="150"/>
      <el-table-column label="老师" align="center" prop="teacherName"/>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="180"/>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="150"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:courses:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:courses:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="88px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类别" prop="typeId">
              <el-select v-model="form.typeId" placeholder="请选择课程分类">
                <el-option
                  v-for="item in courseTypesList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店" prop="storeId">
              <el-select v-model="form.storeId" placeholder="请选择门店">
                <el-option
                  v-for="item in storesList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="标签" prop="tagIds">
              <el-select v-model="form.tagIds" multiple placeholder="请选择课程标签">
                <el-option
                  v-for="item in courseTagsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="链接" prop="link">
              <el-input v-model="form.link" placeholder="请输入链接"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item label="老师" prop="teacherId">
                <el-select v-model="form.teacherId" multiple placeholder="请选择老师">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="周几" prop="week">
              <el-select v-model="form.week" placeholder="请选择周几" clearable>
                <el-option
                  v-for="dict in dict.type.course_time"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="课程时间" prop="courseTimeOptions">
              <el-time-picker
                v-model="form.courseTimeOptions"
                is-range
                format="HH:mm"
                value-format="HH:mm"
                :style="{width: '100%'}"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                range-separator="至"
                clearable
              ></el-time-picker>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--

        -->

        <el-row>
          <el-col :span="8">
            <el-form-item label="位置" prop="address">
              <el-input v-model="form.address" type="textarea" placeholder="请输入位置"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="纬度" prop="lat">{{form.lat}}</el-form-item>
            <el-form-item label="经度" prop="lon">{{form.lon}}</el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="摘要" prop="desc">
              <el-input v-model="form.desc" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="人数限制" prop="num">
              <el-input v-model="form.num" placeholder="请输入人数限制"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="每节价格" prop="price">
              <el-input-number
                :precision="2"
                :min="0.01"
                v-model="form.price"
                placeholder="请输入每节课价格"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="积分支付" prop="canPointPay">
              <el-radio-group v-model="form.canPointPay">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="图片地址" prop="image">
              <image-upload v-model="form.image"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCourses,
  getCourses,
  delCourses,
  addCourses,
  updateCourses
} from "@/api/course/courses";
import { allStores } from "@/api/course/stores";
import { allCourseTypes } from "@/api/course/courseTypes";
import { allCourseTags } from "@/api/course/courseTags";
import { allUser } from "@/api/system/user";

export default {
  name: "Courses",
  dicts: ["sys_yes_no", "onsale_status", "sys_business_status", "course_time"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      courseTagsList: [],
      userList: [],
      storesList: [],
      courseTimeOptions: [],
      courseTypesList: [],
      uploadTime: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      coursesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        typeId: null,
        storeId: null,
        tagIds: null,
        image: null,
        link: null,
        desc: null,
        week: null,
        startTime: null,
        endTime: null,
        timeInfo: null,
        address: null,
        lat: null,
        lon: null,
        sort: null,
        status: null,
        num: null,
        price: null,
        canPointPay: null,
        buyTimes: null,
        adminId: null,
        teacherId: null

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        typeId: [
          { required: true, message: "类别id不能为空", trigger: "blur" }
        ],
        storeId: [
          { required: true, message: "门店id不能为空", trigger: "blur" }
        ],
        tagIds: [
          { required: true, message: "标签ids不能为空", trigger: "blur" }
        ],
        image: [
          { required: true, message: "图片地址不能为空", trigger: "blur" }
        ],
        link: [{ required: true, message: "链接不能为空", trigger: "blur" }],
        address: [{ required: true, message: "位置不能为空", trigger: "blur" }],
        week: [{ required: true, message: "周几不能为空", trigger: "blur" }],
        courseTimeOptions: [
          { required: true, message: "课程时间不能为空", trigger: "blur" }
        ],
        lat: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
        lon: [{ required: true, message: "经度不能为空", trigger: "blur" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        status: [
          {
            required: true,
            message: "状态不能为空",
            trigger: "change"
          }
        ],
        num: [{ required: true, message: "人数限制不能为空", trigger: "blur" }],
        price: [
          { required: true, message: "每节课价格不能为空", trigger: "blur" }
        ],
        canPointPay: [
          {
            required: true,
            message: "可以积分支付不能为空",
            trigger: "blur"
          }
        ],
        adminId: [
          { required: true, message: "创建人id不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "老师id不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.uploadTime[0] = this.getNearDay(-30);
    this.uploadTime[1] = this.getNearDay(0);
    this.getList();
    this.getStoresList();
    this.getCourseTypes();
    this.getCourseTags();
    this.getUserList();
  },
  methods: {
    getUserList() {
      allUser().then(response => {
          this.userList = response.data;
        }
      );
    },

    /** 查询课程列表 */
    getList() {
      this.loading = true;
      if (this.uploadTime) {
        this.queryParams.beginDate = this.uploadTime[0];
        this.queryParams.endDate = this.uploadTime[1];
      } else {
        this.queryParams.beginDate = "";
        this.queryParams.endDate = "";
      }
      listCourses(this.queryParams).then(response => {
        this.coursesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询课程分类列表 */
    getCourseTypes() {
      allCourseTypes().then(response => {
        this.courseTypesList = response.data;
      });
    },

    /** 查询门店列表 */
    getStoresList() {
      allStores().then(response => {
        this.storesList = response.data;
      });
    },

    /** 查询课程标签列表 */
    getCourseTags() {
      allCourseTags().then(response => {
        this.courseTagsList = response.data;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        typeId: null,
        storeId: null,
        tagIds: null,
        image: null,
        link: null,
        desc: null,
        week: null,
        startTime: null,
        endTime: null,
        timeInfo: null,
        address: null,
        lat: 0,
        lon: 0,
        sort: null,
        status: null,
        num: null,
        price: null,
        canPointPay: 2,
        buyTimes: null,
        adminId: null,
        teacherId: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        courseTimeOptions:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCourses(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          if(!this.form.tagIds.includes(",")){
            this.form.tagIds=this.form.tagIds.join(",");
          }
          if (this.form.id != null) {
            updateCourses(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.beginTime=this.form.courseTimeOptions[0];
             this.form.endTime=this.form.courseTimeOptions[1];
            addCourses(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除课程编号为"' + ids + '"的数据项？')
        .then(function() {
          return delCourses(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "course/courses/export",
        {
          ...this.queryParams
        },
        `courses_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
